package com.example.mybaties.testone.aop.cglib;

import com.example.mybaties.testone.aop.common.ForumServiceImpl;
import com.example.mybaties.testone.aop.common.PerformanceMonitor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 这种方式的好处是被代理者不需要实现接口，使用JDK本身的动态代理，被代理者必须实现接口
 */
public class CglibProxy implements MethodInterceptor {

    private Enhancer enhancer = new Enhancer();

    public Object getProxy(Class clz){
        enhancer.setSuperclass(clz);
        enhancer.setCallback(this);
        return enhancer.create();//创建代理的子类实例
    }


    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        PerformanceMonitor.begin(method.getName());
        Object result = methodProxy.invokeSuper(obj, args);//调用父类的方法，而不是invoke()
        PerformanceMonitor.end();
        return result;
    }
}
